package com.chenfan.mcn.job;

import com.chenfan.mcn.clients.datastore.DataStoreServer;
import com.chenfan.mcn.clients.datastore.model.PlatformFansItem;
import com.chenfan.mcn.dao.StarPlatformInfoMapper;
import com.chenfan.mcn.model.StarPlatformInfo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author: tangwei
 * @Date: 2022/5/11 15:03
 * @Description:
 */
@Slf4j
public class StarPlatformFansJob {

    @Autowired
    private DataStoreServer dataStoreServer;

    @Autowired
    private StarPlatformInfoMapper starPlatformInfoMapper;

    /**
     * 更新红人平台信息粉丝数
     */
    @XxlJob(value = "updateStarPlatformInfoFans")
    public ReturnT<String> updateStarPlatformInfoFans(String param) {
        List<StarPlatformInfo> starPlatformInfoList = starPlatformInfoMapper.selectAll();
        starPlatformInfoList.forEach(starPlatformInfo -> {
            try {
                List<PlatformFansItem> platformFansItemList = dataStoreServer.getDcMcnFans(starPlatformInfo.getPlatformId(), starPlatformInfo.getStarPlatformId());
                if (!CollectionUtils.isEmpty(platformFansItemList)) {
                    starPlatformInfo.setFansQuantity(
                            divTenThousand(BigDecimal.valueOf(platformFansItemList.get(0).getPFansNum() == null ? 0 : platformFansItemList.get(0).getPFansNum())));
                    starPlatformInfoMapper.updateById(starPlatformInfo);
                }
            } catch (Exception e) {
                log.error("红人信息更新失败：", e);
                XxlJobLogger.log(e);
                XxlJobLogger.log(starPlatformInfo.toString());
            }
        });
        return ReturnT.SUCCESS;
    }

    private static BigDecimal divTenThousand(BigDecimal value) {
        return value.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP);
    }
}